<template>
    <view class="api-select">
        <u-popup :show="show" :round="20" mode="bottom" @touchmove.stop.prevent="movehandle">
            <view class="box">
                <view class="header">
                    <view class="left">请选择{{ title }}</view>
                    <view class="right" @click="close"><u-icon name="close" size="20"></u-icon></view>
                </view>
                <view class="content">
                    <view class="search-div">
                        <u-search placeholder="搜索" v-model="keyword" :showAction="false" clearabled @search="handleSearch" @clear="handleSearch" @change="handleSearch"></u-search>
                    </view>
                    
                    <view v-for="(item,index) of columns" :key="index" class="item" @click="handleSelected(item)">
                        <view v-if="props.multiple">
                            <text :class="selectedValItem.length && selectedValItem.map(e=>e.id).includes(item.id)?'selected':''">{{ item.name }}</text>
                            <!-- <img v-if="selectedValItem.length && selectedValItem.map(e=>e.id).includes(item.id)"  src="https://zxtest001.oss-cn-beijing.aliyuncs.com/l-owner-uni3/greenDuipng" class="duihao"> -->
                        </view>
                        <view v-else>
                            <text :class="item.id===selectedValItem.id?'selected':''">{{ item.name }}</text>
                            <!-- <img v-if="item.id===selectedValItem.id"  src="https://zxtest001.oss-cn-beijing.aliyuncs.com/l-owner-uni3/greenDuipng" class="duihao"> -->
                        </view>
                        
                    </view>
                </view>
                <view class="footer">
                    <view class="btn" @click="confirm">确定</view>
                </view>
            </view>
            <toast :data="tipobj" v-model:show="showToast"></toast> <!--toast 要写在 popup 组件里面，否则层级被覆盖-->
        </u-popup>
        
    </view> 
</template>

<script setup lang="ts">
/**
 * @author:  wyr
 * @description 【H5组件】枚举选择组件 ()
 * @param { object} props - 
 * @param { Boolean} show - 双向绑定的数据，控制弹窗开关
 * @desc - 使用方式 用法与pc端类似，不同点：不论是多选还是单选，默认值defaultVal只能是数组   payfees.vue 在这个页，有测试数据
 */

 import { watch,ref,reactive } from 'vue';
 import toast from '@/component/common/toast/toast';
 const props = defineProps({
    defaultVal:{ type:Array, default:()=>[]},   // 默认值 必须是数组
    fetch:{ type:Function, required: true},  // 对应fetchMix的值
    showFlag:{ type:Boolean, default:false},  // 双向绑定的数据,控制弹窗打开关闭
    hasObj:{ type:Boolean, default:false},  // 是否要整个一行的数据
    multiple:{ type:Boolean, default:false},  // 是否多选
    placeholder:{ type:String, default:'请选择'}, 
    query:{ type:Object, default:() => {}}, // 查询条件
    title:{ type:String, default:''}, // 标题
})
const showToast = ref<boolean>(false);  // 提示错误信息弹窗打开关闭
let tipobj = reactive<any>({});  // 提示信息toast 数据

const show = ref<boolean>(false); 
const columns = ref<any[]>([]); // 全部数据
const selectedValItem = props.multiple ? ref<any>([]) : reactive<any>({});  // 选中的数据
let keyword = ref<string>('');  // 搜索关键字

const emit = defineEmits(['update:showFlag','on-confirm', 'on-mounted'])
const movehandle = () => {}
// 选中
const handleSelected = (val:any)=>{
    if(props.multiple){
        if(selectedValItem.value.length){
            if(selectedValItem.value.map((res:any)=>res.id).includes(val.id)){  // 如果在选中的数据中，已经有这条数据，那删除这条数据
                selectedValItem.value = selectedValItem.value.filter((res:any)=>res.id !== val.id)
            }else{  // 没有这条数据，那追加               
                selectedValItem.value.push(val);
            }
        }else{
            selectedValItem.value=[val];
        }
    }else{
        Object.assign(selectedValItem, val)  // 对象赋值，用这种方式
    }
}

// 取消
const close = ()=>{
    show.value = false;
    emit('update:showFlag',show.value);
}

//提示
const handleToast = ()=>{
    showToast.value = true;  
    tipobj={
        type:'error',
        message: '请选择数据',
    } 
}

// 点击确认
const confirm = ()=>{
    // if((props.multiple && !selectedValItem.value.length) || (!props.multiple && !selectedValItem.id)){
    //     handleToast();
    //     return false;
    // }
    if(props.multiple){
        emit('on-confirm',props.hasObj ? selectedValItem.value : selectedValItem.value.map((e:any)=>e.id));
        selectedValItem.value = [];
    }else{
        emit('on-confirm',props.hasObj ? selectedValItem : selectedValItem.id);
        Object.assign(selectedValItem,{});
    }
    close();
}

//搜索
const handleSearch =(val:string)=>{ 
    keyword.value = val;
    if(!keyword.value){
        onRefresh();
    }else{
        columns.value = columns.value.filter((res:any)=>res.name.includes(keyword.value));
        
    } 
}

const onRefresh = async()=> {
    try {
      const data = await fetchData(props.query);
      columns.value = data;
    } catch (err) {
      throw err;
    } 
  }

const fetchData = async(query:any)=> {
  const fetch:any =  props.fetch;
  if (typeof fetch === 'function') {
    const data = await fetch({
      ...query,
      
      page_num: 9999
    });
    emit('on-mounted', data)
    return data;
  } else {
    return [];
  }
}

watch(()=>props.showFlag , async(newVal,oldVal)=>{
    if(newVal){            
        show.value = true;
        await onRefresh();
        for(const item of columns.value){
            for(const res of props.defaultVal){
                if(item.id === res){
                    if(props.multiple){
                        selectedValItem.value.push(item)
                    }else{
                        Object.assign(selectedValItem,item);
                        break;
                    }
                    
                }
            }
        }
        
    }
},{immediate:true})





</script>
<style lang="scss">
.api-select{
    
    .box{
        width: 100%;
        height: 800rpx;
        font-size: $uni-font-size-lg;
        .header{
            padding: 42rpx 30rpx 24rpx;
            background: url('https://asa-hr.oss-cn-beijing.aliyuncs.com/HR-h5/title.png') 30rpx 46rpx no-repeat;
            background-size: 5px;
            overflow: hidden;
            .left{
                float: left;
                padding-left: 24rpx;
                height: 52rpx;
                line-height: 38rpx;
                font-weight: 500;
            }
            .right{
                float: right;
                height: 52rpx;
            }
        }
        .content{
            height: 580rpx;
            margin: 0 24rpx;
            overflow: auto;
            .search-div{
                margin: 0 30rpx;
            }
            .item{
                height: 120rpx;
                line-height: 120rpx;
                border-bottom: 2rpx solid #f3f3f3;
                text-align: center;
                color: $uni-text-color;
                position: relative;
                .duihao{
                    position: absolute;
                    right: 36rpx;
                    width: 40rpx;
                    height: 40rpx;
                    margin-top: 40rpx;
                }
                .selected{
                    color: #0000A6;
                    font-family: PingFangSC-Medium, PingFang SC;
                    font-weight: 500;
                }
            }
            .item:last-child{
                border: none;
            }
        }
        .footer{
            padding: 24rpx;
            .btn{
                height: 84rpx;
                line-height: 84rpx;
                width: 100%;
                font-weight: 500;
                text-align: center;
                font-family: PingFangSC-Medium, PingFang SC;
                color: $uni-text-color-inverse;
                // background: linear-gradient(142deg, #2D79E6 0%, #0B308E 100%);
                background: #0000A6;
                border-radius: 20rpx;
            }
        }
    }
    
}
  

</style>
